<template>
	<view class="share">
		<!-- 导航栏 -->
		<!-- navBar title="生成海报" color="#fff" background="transparent" isBack backColor="#fff"></navBar> -->
		<nav-bars  bgColor="#fff" fontColor="#000" title="生成海报"></nav-bars>
		
		<!-- 背景 -->
		<view class="s_bg"></view>
		
		<!-- 内容 -->
		<view class="s_content">
			<view class="s_cPicture">
				<view class="s_cImage"><image :src="datas.thumb_url[0].path||'https://cos.ryz1620.com/liankun/static/IMG279.png'"></image></view>
				<view class="s_cUser">
					<view class="s_cHead"><image :src="img2||'https://cos.ryz1620.com/liankun/static/IMG280.png'"></image></view>
					<view class="s_cName">{{datas.decoration_name||'***'}}</view>
				</view>
				<view class="s_cText2 omit-1">{{datas.title}}</view>
				<view class="s_cChecklist">
					<view class="s_ccItem">
						<view class="s_ccTit">户型</view>
						<view class="s_ccTxt">{{datas.house_type}}</view>
					</view>
					<view class="s_ccItem">
						<view class="s_ccTit">面积</view>
						<view class="s_ccTxt">{{datas.area}}m²</view>
					</view>
					<view class="s_ccItem">
						<view class="s_ccTit">报价</view>
						<view class="s_ccTxt">{{datas.offer}}万</view>
					</view>
					<view class="s_ccItem">
						<view class="s_ccTit">风格</view>
						<view class="s_ccTxt"><text v-for="(item,index) in datas.design_style" :key="index" v-if="index<2&&datas.design_style">{{item.name}}</text></view>
					</view>
				</view>
				<view class="s_cBtm">
					<view class="s_cCode"><image :src="datas.wx_code_url"></image></view>
					<view class="s_cTip">
						<view>长按小程序码</view>
						<view>查看Ta的分享</view>
					</view>
					<view class="s_cLogo">融易装</view>
				</view>
			</view>
			<view class="s_cFuns">
				<view class="s_cfClose" @tap="goBack">
					<view class="s_cfBtn"><view class="s_cfIcon iconfont icon-cancel2"></view></view>
					<view class="s_cfTxt">取消</view>
				</view>
				<view class="s_cfSave"  @tap="download">
					<view class="s_cfBtn"><view class="s_cfIcon iconfont icon-save"></view></view>
					<view class="s_cfTxt">保存到相册</view>
				</view>
			</view>
		</view>
		
		<!-- canvas -->
		<view class="s_canvas">
			<view class="s_cCan">
				<canvas canvas-id="myPoster" :style="{'width': canvasWidth + 'px', 'height': canvasHeight + 'px'}"></canvas>
			</view>
		</view>
	</view>
</template>

<script>
// import navBar from "@/components/navBar/navBar"
import service_design from '@/service/design'
import service_decoration from '@/service/decoration.js'
	
export default {
	data() {
		return {
			systemInfo: null,
			// canvas
			canvasCtx: null,
			canvasWidth: 640,
			canvasHeight: 940,
			caseId:'',
			datas:'',
			img1:'',
			// img2:'../../../../static/my/toux.png',
			img2:'',
			img3:'',
			design_style:'',
		}
	},
	
	// components: { navBar },
	onLoad(params) {
		this.$utils.getUrl()
		this.caseId = params.caseId
		this.getshare()
	},
	onReady() {
		let _this = this
		if (!_this.canvasCtx) _this.canvasCtx = uni.createCanvasContext('myPoster')
		if (!_this.systemInfo) {
			uni.getSystemInfo({
				success(res) {
					_this.systemInfo = res
				}
			})
		}
	},
	
	methods: {
		// 分享
		getshare() {
			let that = this
			service_decoration.getTeamShare({ case_id:this.caseId})
				.then(res => {	
					this.datas =res.data
					if(res.data.design_style.length>0){
						this.design_style = res.data.design_style[0].name
					}else{
						this.design_style = '无'
					}
					if(res.data.thumb_url.length>1){
						this.img1 = res.data.thumb_url[0].path
					}else{
					   this.img1 = 'https://cos.ryz1620.com/liankun/static/IMG279.png'
					}
					if(res.data.avatar){
						that.img2 =res.data.avatar.path
					}else{
						that.img2='https://cos.ryz1620.com/liankun/static/IMG280.png'
					}
					that.img3 =  res.data.wx_code_url
					this.datas =res.data
					
			})
		},
		// 返回
		goBack() {
			uni.navigateBack()
		},
		
		// 下载
		download() {
			let _this = this
			
			uni.getSetting({
				success(res) {
					// 没有权限 => 获取权限
					if (!res.authSetting['scope.writePhotosAlbum']) {
						uni.authorize({
							scope: 'scope.writePhotosAlbum',
							success() {
								_this.createPicture()
							},
							fail() {
								uni.showModal({ title: '提示：', content: "授权失败，请前往设置中心设置权限", confirmText: '前往授权',
									success(res) {
										if (res.confirm) {
											uni.openSetting()
										}
										else {
											uni.showToast({ title: '保存失败，没有权限!', icon: 'none' })
										}
									}
								})
							}
						})
					}
					else {
						_this.createPicture()
					}
				}
			}) 	
		},
		
		// 生成分享海报
		createPicture() {
			let _this = this
			
			uni.showLoading({ title: '海报绘制中...', mask: true })
			_this.drawCanvas(() => {
				if (!_this.systemInfo) _this.systemInfo = uni.getSystemInfoSync()
				let pixelRatio = _this.systemInfo ? _this.systemInfo.pixelRatio : 2
				// 生成图片
				uni.canvasToTempFilePath({
					canvasId: 'myPoster',
					width: _this.canvasWidth,
					height: _this.canvasHeight,
					destWidth:  _this.canvasWidth * pixelRatio,
					destHeight:  _this.canvasHeight * pixelRatio,
					success(res) {
						let tempFilePath = res.tempFilePath
						// 保存图片到相册
						uni.saveImageToPhotosAlbum({
							filePath: tempFilePath,
							success() {
								uni.hideLoading()
								uni.showToast({ title: '海报生成成功，图片已放入您的相册', icon: 'none' })
							}
						})
					}
				})
			})
		},
		//获取图片
		getImageInfo(imgSrc){
			return new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: imgSrc,
					success: (image) => {
						resolve(image);
						console.log('获取图片成功',image)
					},
					fail: (err) => {
						reject(err);
						console.log('获取图片失败',err)
					}
				});
			});
		},
		// 绘制canvas
		async drawCanvas(callback) {
			let that = this
			let ctx = that.canvasCtx ? that.canvasCtx : uni.createCanvasContext('myPoster')
			if (!that.canvasCtx) that.canvasCtx = ctx

			let ctxWidth = that.canvasWidth   
			let ctxHeight = that.canvasHeight 
		
			// 清空canvas内容=====
			ctx.clearRect(0, 0, ctxWidth, ctxHeight)
		
			// ctx.scale(.5, .5)
		
			// 绘制最外层盒子=====
			let boxW = ctxWidth
			let boxH = ctxHeight
			let boxRadius = 16
			let boxBack = "#fff"
			let boxX = 0
			let boxY = 0
			let boxLeft = 0
			let boxTop = 0
			ctx.save()
			ctx.rect(boxX, boxY, boxW, boxH)
			ctx.setFillStyle(boxBack)
			ctx.fill()
			ctx.restore()
			ctx.draw(true)
			
			// 绘制大图=====
			let b_imageMl = 28
			let b_imageMt = 28
			let b_imageX = boxLeft + b_imageMl
			let b_imageY = boxTop + b_imageMt
			let b_imageW = 584
			let b_imageH = 484
			let b_imageRadius = 16
			let b_imageBg = "#f0f0f0"
			let b_imageSrc = await that.getImageInfo(that.img1)
			ctx.save()
			that.roundRect(ctx, b_imageX, b_imageY, b_imageW, b_imageH, b_imageRadius)
			ctx.clip()
			ctx.drawImage(b_imageSrc.path, b_imageX, b_imageY, b_imageW, b_imageH)
			ctx.restore()
			ctx.draw(true)
			// 重新计算盒子top信息
			boxTop = b_imageY + b_imageH  
			
			// 用户信息=====
			// 绘制用户头像容器
			let b_headMl = 28
			let b_headMt = -40
			let b_headW = 80
			let b_headH = 80
			let b_headX = boxLeft + b_headMl
			let b_headY = boxTop + b_headMt
			let b_headRadius = 40
			let b_headBg = "#fff"
			let b_headIsPosition = true
			ctx.save()
			ctx.arc(b_headX + b_headRadius, b_headY + b_headRadius, b_headRadius, 0, 2 * Math.PI)
			ctx.setFillStyle(b_headBg)
			ctx.fill()
			ctx.restore()
			ctx.draw(true)
			// 绘制用户头像
			let b_headimgMl = 32
			let b_headimgMt = -36
			let b_headimgW = 72
			let b_headimgH = 72
			let b_headimgX = boxLeft + b_headimgMl
			let b_headimgY = boxTop + b_headimgMt
			let b_headimgRadius = 36
			let b_headimgBg = "#f0f0f0"
			let b_headimgSrc = await that.getImageInfo(that.img2)
			let b_headimgIsPosition = true
			ctx.save()
			ctx.arc(b_headimgX + b_headimgRadius, b_headimgY + b_headimgRadius, b_headimgRadius, 0, 2 * Math.PI)
			ctx.setFillStyle(b_headimgBg)
			ctx.fill()
			ctx.clip()
			ctx.drawImage(b_headimgSrc.path, b_headimgX, b_headimgY, b_headimgW, b_headimgH)
			ctx.restore()
			ctx.draw(true)
			// 绘制用户名
			let b_nameText = that.datas.designer_name||'****'
			let b_nameFontSize = 24
			let b_nameFont = 'bold ' + b_nameFontSize + 'px sans-serif'
			let b_nameMt = 6
			let b_nameMl = 124
			let b_nameLh = 34
			let b_nameX = boxLeft + b_nameMl
			let b_nameY = boxTop + b_nameMt
			ctx.save()
			ctx.font = b_nameFont
			ctx.setFillStyle("#333")
			ctx.setFontSize(b_nameFontSize)
			ctx.setTextBaseline('top')
			ctx.fillText(b_nameText, b_nameX, b_nameY + ((b_nameLh - b_nameFontSize) / 2))
			ctx.restore()
			ctx.draw(true)
			// 重新计算盒子top信息
			boxTop = b_nameY + b_nameLh 
			
			// 内容=====
			let b_contText = that.datas.title
			let b_contFontSize = 24
			let b_contMt = 28
			let b_contMl = 32
			let b_contWidth = 576
			let b_contLh = 32
			let b_contX = boxLeft + b_contMl
			let b_contY = boxTop + b_contMt
			ctx.save()
			ctx.setFillStyle("#6c6c6c")
			ctx.setTextBaseline('top')
			that.dealWords({
				ctx,
				fontSize: b_contFontSize,
				word: b_contText,
				maxWidth: b_contWidth,
				x: b_contX,
				y: b_contY + ((b_contLh - b_contFontSize) / 2),
			})
			ctx.restore()
			ctx.draw(true)
			// 重新计算盒子top信息
			boxTop = b_contY + b_contLh 
			
			// 列表=====
			let b_listMt = 16
			let b_listMl = 28
			let b_listW = 584
			let b_listH = 96
			let b_listX = boxLeft + b_listMl
			let b_listY = boxTop + b_listMt
			let b_listBg = "#f6f7fb"
			let b_listRadius = 8
			let b_listTit1 = "户型"
			let b_listTit2 = "面积"
			let b_listTit3 = "报价"
			let b_listTit4 = "风格"
			let b_listTitMt = 16
			let b_listVal1 = that.datas.house_type
			let b_listVal2 = that.datas.area + 'm²'
			let b_listVal3 = that.datas.offer + '万'
			let b_listVal4 = that.design_style
			let b_listValMt = 52
			ctx.save()
			// 绘制背景
			that.roundRect(ctx, b_listX, b_listY, b_listW, b_listH, b_listRadius)
			ctx.setFillStyle(b_listBg)
			ctx.fill()
			// 绘制标题
			ctx.setFontSize(20)
			ctx.setTextAlign('center')
			ctx.setTextBaseline('top')
			ctx.setFillStyle("#939393")
			ctx.fillText(b_listTit1, b_listX + (b_listW / 8) , b_listY + b_listTitMt)
			ctx.fillText(b_listTit2, b_listX + (b_listW / 8) * 3, b_listY + b_listTitMt)
			ctx.fillText(b_listTit3, b_listX + (b_listW / 8) * 5, b_listY + b_listTitMt)
			ctx.fillText(b_listTit4, b_listX + (b_listW / 8) * 7, b_listY + b_listTitMt)
			// 绘制内容
			ctx.setFillStyle("#333")
			ctx.fillText(b_listVal1, b_listX + (b_listW / 8) , b_listY + b_listValMt)
			ctx.fillText(b_listVal2, b_listX + (b_listW / 8) * 3, b_listY + b_listValMt)
			ctx.fillText(b_listVal3, b_listX + (b_listW / 8) * 5, b_listY + b_listValMt)
			ctx.fillText(b_listVal4, b_listX + (b_listW / 8) * 7, b_listY + b_listValMt)
			ctx.restore()
			ctx.draw(true)
			// 重新计算盒子top信息
			boxTop = b_listY + b_listH 
			
			// 分割线=====
			let b_lineMt = 40
			let b_lineX = boxLeft
			let b_lineY = boxTop + b_lineMt
			let b_lineBg = "#f4f4f4"
			ctx.save()
			ctx.rect(b_lineX, b_lineY, boxW, 1)
			ctx.setFillStyle(b_lineBg)
			ctx.fill()
			ctx.restore()
			ctx.draw(true)
			// 重新计算盒子top信息
			boxTop = b_lineY 
			
			// logo=====
			let b_logoText = "融易装"
			let b_logoMt = 60
			let b_logoMl = 32
			let b_logoLh = 56
			let b_logoFontSize = 40
			let b_logoFont = 'bold ' + b_logoFontSize + 'px sans-serif'
			let b_logoX = boxLeft + b_logoMl
			let b_logoY = boxTop + b_logoMt
			let b_logoIsPosition = true
			ctx.save()
			ctx.font = b_logoFont
			ctx.setFontSize(b_logoFontSize)
			ctx.setFillStyle("#333")
			ctx.setTextBaseline('top')
			ctx.fillText(b_logoText, b_logoX, b_logoY + ((b_logoLh - b_logoFontSize) / 2))
			ctx.restore()
			ctx.draw(true)
			
			// 提示=====
			let b_tipText1 = "长按小程序码"
			let b_tipText2 = "查看Ta的分享"
			let b_tipMt = 54
			let b_tipMl = 320
			let b_tipLh = 36
			let b_tipFontSize = 24
			let b_tipX = boxLeft + b_tipMl
			let b_tipY = boxTop + b_tipMt
			let b_tipIsPosition = true
			ctx.save()
			ctx.setFontSize(b_tipFontSize)
			ctx.setFillStyle("#939393")
			ctx.setTextBaseline('top')
			ctx.fillText(b_tipText1, b_tipX, b_tipY + ((b_tipLh - b_tipFontSize) / 2))
			ctx.fillText(b_tipText2, b_tipX, b_tipY + b_tipLh + ((b_tipLh - b_tipFontSize) / 2))
			ctx.restore()
			ctx.draw(true)
			
			// 小程序码=====
			let b_codeMl = 492
			let b_codeMt = 28
			let b_codeX = boxLeft + b_codeMl
			let b_codeY = boxTop + b_codeMt
			let b_codeW = 120
			let b_codeH = 120
			let b_codeBg = "#f0f0f0"
			let b_codeSrc = await that.getImageInfo(that.img3)
			ctx.save()
			ctx.rect(b_codeX, b_codeY, b_codeW, b_codeH)
			ctx.clip()
			ctx.drawImage(b_codeSrc.path, b_codeX, b_codeY, b_codeW, b_codeH)
			ctx.restore()
			ctx.draw(true, () => {
				if (typeof callback === 'function') {
					setTimeout(() => {
						callback()
					}, 100)
				}
			})
		},
		
		// 圆角矩形
		roundRect(ctx, x, y, w, h, r) {
			let min_size = Math.min(w, h)
			if (r > min_size / 2) r = min_size / 2
			ctx.beginPath()
			ctx.moveTo(x + r, y)
			ctx.arcTo(x + w, y, x + w, y + h, r)
			ctx.arcTo(x + w, y + h, x, y + h, r)
			ctx.arcTo(x, y + h, x, y, r)
			ctx.arcTo(x, y, x + w, y, r)
			ctx.closePath()
		},
			
		//处理文字多出省略号显示
		dealWords({ ctx, fontSize, line, word, maxWidth, x, y, maxLine = 1 } = {}) {
			line = line ? line : fontSize
			ctx.setFontSize(fontSize)  // 设置字体大小
			let allRow = Math.ceil(ctx.measureText(word).width / maxWidth)  // 实际总共能分多少行
			let count = allRow >= maxLine ? maxLine : allRow  // 实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
			let endPos = 0  // 当前字符串的截断点
			for (let j = 0; j < count; j++) {
				let nowStr = word.slice(endPos)  // 当前剩余的字符串
				let rowWid = 0  // 每一行当前宽度    
				if (ctx.measureText(nowStr).width > maxWidth) {  // 如果当前的字符串宽度大于最大宽度，然后开始截取
					for (let m = 0; m < nowStr.length; m++) {
						rowWid += ctx.measureText(nowStr[m]).width  // 当前字符串总宽度
						if (rowWid > maxWidth) {                 
							if (j === maxLine - 1) {  // 如果是最后一行
								ctx.fillText(nowStr.slice(0, m - 1) + '...', x, y + j * line)   // (j+1)*18这是每一行的高度        
							} else {
								ctx.fillText(nowStr.slice(0, m), x, y + j * line)
							}
							endPos += m  // 下次截断点
							break
						}
					}
				} else { // 如果当前的字符串宽度小于最大宽度就直接输出
					ctx.fillText(nowStr.slice(0), x, y + j * 18);
				}
			}
		},
	}
}
</script>

<style lang="scss" scoped>
	
// 背景=====
.share .s_bg {width: 100vw;height: 100vh;background: linear-gradient(180deg, #1A212D 0%, #A2A5AA 100%);position: fixed;top: 0;left: 0;z-index: 1;}


// 内容=====
.share .s_content {padding-top: 72rpx;position: relative;z-index: 2;
    .s_cPicture {width: 640rpx;margin-left: 56rpx;border-radius: 16rpx;background: #fff;box-shadow: 0 0 12rpx rgba(0, 0, 0, .16);overflow: hidden;}
    .s_cImage {width: 584rpx;height: 484rpx;margin: 28rpx 0 0 28rpx;border-radius: 16rpx;background: #f0f0f0;}
    .s_cUser {height: 34rpx;line-height: 34rpx;font-size: 24rpx;font-weight: bold;padding-left: 124rpx;margin-top: 6rpx;position: relative;}
    .s_cHead {width: 80rpx;height: 80rpx;border: 4rpx solid #fff;border-radius: 50%;background: #f0f0f0;position: absolute;bottom: 0;left: 28rpx;overflow: hidden;}
	// 标签
    .s_cTags {padding: 20rpx 28rpx 0;overflow: hidden;}
    .s_ctTag {height: 44px;height: 44rpx;line-height: 44rpx;color: #a58f6d;font-size: 24rpx;padding-left: 48rpx;margin: 8rpx 8rpx 0 0;border-radius: 22rpx;background: #f9f6f3;position: relative;float: left;}
    .s_ctIcon {width: 36rpx;height: 36rpx;position: absolute;top: 4rpx;left: 4rpx;}
	// 清单
    .s_cChecklist {height: 96rpx;padding-top: 16rpx;margin: 16rpx 28rpx 0;border-radius: 8rpx;background: #f6f7fb;box-sizing: border-box;display: flex;}
    .s_ccItem {flex: 1;}
    .s_ccTit,     .s_ccTxt {height: 28rpx;line-height: 28rpx;text-align: center;color: #939393;font-size: 20rpx;}
    .s_ccTxt {color: #333;margin-top: 8rpx;}
	// 设计动态
    .s_cText1 {height: 32rpx;line-height: 32rpx;color: #6c6c6c;font-size: 24rpx;margin: 16rpx 32rpx 0;}
	// 案例详情
    .s_cText2 {height: 32rpx;line-height: 32rpx;color: #6c6c6c;font-size: 24rpx;margin: 28rpx 32rpx 0;}
    .s_cBtm {height: 176rpx;margin-top: 40rpx;position: relative;
		&::before {content: "";width: 100%;height: 1px;background: #f4f4f4;position: absolute;top: 0;left: 0;}
	}
    .s_cCode {width: 120rpx;height: 120rpx;margin: 28rpx 28rpx 0 0;float: right;}
    .s_cTip {line-height: 36rpx;color: #939393;font-size: 24rpx;margin: 54rpx 20rpx 0 0;float: right;}
    .s_cLogo {height: 176rpx;line-height: 176rpx;font-size: 40rpx;font-weight: bold;padding-left: 32rpx;}
    .s_cFuns {padding: 60rpx 120rpx 30rpx;overflow: hidden;}
    .s_cfClose,
    .s_cfSave {padding: 20rpx;position: relative;float: left;
		&:active {opacity: .88;}
		.s_cfBtn {width: 112rpx;height: 112rpx;color: #ccc;border-radius: 50%;background: #fff;box-shadow: 0 0 12rpx rgba(0, 0, 0, .16);display: flex;justify-content: center;align-items: center;}
		.s_cfIcon {font-size: 72rpx;}
		.s_cfTxt {height: 34rpx;line-height: 34rpx;text-align: center;color: #fff;font-size: 24rpx;margin-top: 16rpx;}
	}
    .s_cfSave {float: right;
		.s_cfBtn {background: #ffd425;color: #fff;}
	}
}

// canvas
.share .s_canvas {position: relative;overflow: hidden;
	.s_cCan {position: absolute;top: 10000px;left: 10000px;}
}
</style>